package yxy.cherry.paycenter.servlet.channel.jhh5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.jhh5.PayMoudle_jhh5;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;

public class Servlet_jhh5 extends Servlet {

	private static final Logger logger = Logger.create(Servlet_jhh5.class);
	
	private static final int success = 1;	//交易结果 成功
	private static final int fail = 2;	//交易结果 失败
	
	public Servlet_jhh5() {
//		SdkService.getInstance().addServlet("/jh", new Servlet_jh());
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpUtil.printlnParseMap("post jhh5", req);
		JSONObject infoobj = HttpUtil.getParseJSON(req);

		JSONObject returnjson = new JSONObject();
		
//		参数			类型		必填	参与签名	备注
//		appId		String	Y			商户在支付平台申请的应用 ID
//		payNo		String	Y			支付平台的交易订单号
//		orderNo		String	Y	Y		商户的订单号
//		userName	String	Y	Y		用户名称
//		result		int		Y	Y		交易结果 1 表示成功，2 表示失败
//		pay_channel	String	Y	Y		值由 orderType 决定，orderType=1 时为支 付简码；orderType=2 时为渠道简码。具体 参看附录
//		amount		String	Y	Y		支付金额（单位元）
//		pay_time	String	Y	Y		支付时间，格式 yyyy-MM-dd HH:mm:ss
//		userpara	String	Y			透传参数，原样回传
//		orderType	int		Y			订单类型：1 平台订单；2 联运渠道订单
//		sign		String	Y			签名，具体参看签名算法说明
		
		if(!infoobj.containsKey("appId")) {
			returnFail(resp);
			return;
		}
		String appid = infoobj.getString("appId");	
		
		if(!infoobj.containsKey("payNo")) {
			returnFail(resp);
			return;
		}
		String payNo = infoobj.getString("payNo");	
		
		if(!infoobj.containsKey("orderNo")) {
			returnFail(resp);
			return;
		}
		String orderNo = infoobj.getString("orderNo");	
		
		if(!infoobj.containsKey("userName")) {
			returnFail(resp);
			return;
		}
		String userName = infoobj.getString("userName");	
		
		if(!infoobj.containsKey("result")) {
			returnFail(resp);
			return;		
		}
		int result = infoobj.getIntValue("result");
		
		if(!infoobj.containsKey("pay_channel")) {
			returnFail(resp);
			return;
		}
		String pay_channel = infoobj.getString("pay_channel");
		
		if(!infoobj.containsKey("amount")) {
			returnFail(resp);
			return;
		}
		String amount = infoobj.getString("amount");
		
		if(!infoobj.containsKey("pay_time")) {
			returnFail(resp);
			return;
		}
		String pay_time = infoobj.getString("pay_time");
		
		if(!infoobj.containsKey("userpara")) {
			returnFail(resp);
			return;
		}
		String userpara = infoobj.getString("userpara");
		
		if(!infoobj.containsKey("orderType")) {
			returnFail(resp);
			return;
		}
		int orderType = infoobj.getInteger("orderType");
		
		if(!infoobj.containsKey("sign")) {
			returnFail(resp);
			return;
		}
		String sign = infoobj.getString("sign");
		
		orders o = ordersDao.getOrderByMyorderid(orderNo);
		if(o == null) {
			//订单不存在
			logger.info("jhh5 no order " + orderNo);
			returnFail(resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			//订单已完成
			logger.info("jhh5 order finished " + orderNo);
			returnSuccess(resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			//订单失败
			logger.info("jhh5 order fail " + orderNo);
			returnFail(resp);
			return;
		}
		
//		(4)签名算法 
//		交易最终结果以 MD5 方式签名，签名算法如下（只需参数值参与签名）： 
//		sign= MD5(orderNo + userName + result + amount + pay_time + pay_channel + openKey) 
//		(5)返回内容 
//		返回结果	结果说明
//		ok	处理成功，系统收到此结果后不再后续通知。返回结果不区分大小写。
//		fail 或 其 它 字 符	处理不成功，系统收到此结果或者没有收到任何结果，会通过补单机制 再次通知（具体详见回传机制），请商户处理好重复通知的情况。

//		String openKey = gameconfig.getParam("jhh5_openkey", 0);		
		String openKey = getOpenKey(appid);
		//SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_1_openkey);
		
		//待签名字符串
		String signstr = orderNo + userName + result + amount + pay_time + pay_channel + openKey;
		
		//重新签名
		String newsign = HttpUtil.getMD5(signstr).toLowerCase();
		
		//校验参数
		if(!newsign.equals(sign)) {
			System.out.println("-----------jhh5 deal pay------------" + newsign + "---------" + sign + "----");
			returnFail(resp);
			return;
		}
		
		//核对平台结果
		if(result != success) {
			returnFail(resp);
			return;
		}
		
		double dpayamount = Double.valueOf(amount) * 100;
		int payamount = (int) dpayamount;
		
		o.setPlatorderid(payNo);
		o.setUpdatetime(new Date());
		o.setPayamount(payamount);
		o.setSubchannel(o.getChannel());
		o.setOrderstate(OrderInfoModule.orderinfofinish);
		ordersDao.update(o);
		
		ActType at = ActType.getat(o.getActtype());
		PayMoudle_jhh5 am = new PayMoudle_jhh5();
		ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());
		
		charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
		am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());
		
		returnSuccess(resp);
	}

	public void returnSuccess(HttpServletResponse resp) {
		returnInfo("ok", resp);
	}
	
	public void returnFail(HttpServletResponse resp) {
		returnInfo("fail", resp);
	}
	
	/**
	 * 返回信息到渠道
	 * 
	 * @param data
	 * @param resp
	 */
	public void returnInfo(String data, HttpServletResponse resp) {
		PrintWriter pw = null;
		resp.addHeader("Access-Control-Allow-Origin", "*");

		try {
			pw = resp.getWriter();
			pw.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	@Override
	public String getChannel() {
		return SdkChannel.sdk_jhh5;
	}
	
	
	private String getOpenKey(String appid) {
		if(appid.equals(SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_1_appid))) {
			return SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_1_openkey);
		}
		
		if(appid.equals(SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_2_appid))) {
			return SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_2_openkey);
		}
		
		if(appid.equals(SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_3_appid))) {
			return SDKParm.getSdkparmvalue(SdkParmEnum.jhh5_3_openkey);
		}
		
		return "";
	}
}
